package com.csw.android.blur

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.util.AttributeSet
import android.widget.FrameLayout

class BlurTargetLayout @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {

    var onPictureUpdateListener: OnPictureUpdateListener? = null
        set(value) {
            field = value
            requestPicture()
        }

    fun requestPicture() {
        noticePictureUpdate()
    }

    private fun noticePictureUpdate() {
        onPictureUpdateListener?.run {
            val w = width
            val h = height
            if (w > 0 && h > 0) {
                val bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
                val canvas = Canvas(bitmap)
                draw(canvas)
                onPictureUpdate(bitmap)
            }
        }
    }

    interface OnPictureUpdateListener {
        fun onPictureUpdate(bitmap: Bitmap)
    }
}